<script setup>
import { io } from 'socket.io-client'
import { useRoute} from 'vue-router'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import {ref } from "vue";

const $route = useRoute()
const { username } = $route.query
const socket = io("ws://127.0.0.1:3333/videoroom");
const socketId=ref("")
socket.on("connect", () => {
    socketId.value=socket.id
});
socket.on("disconnect", () => {});
const userMap = ref({})
socket.emit("init", { username })
socket.on("updateUser", (newUserMap) => {
    userMap.value = newUserMap
})
const videoRef = ref(null)
const videoRef2=ref(null)
let stream=ref(null)

//作为主持人
const hostPeerConnection= new RTCPeerConnection()
const sendOffer=async (stream)=>{                        //发送offer
    stream.getTracks().forEach(track=>{                  //hostRTC加入stream数据流
        hostPeerConnection.addTrack(track,stream)
    })
    const offer=await hostPeerConnection.createOffer()
    await hostPeerConnection.setLocalDescription(offer)
    await socket.emit("sendOffer",hostPeerConnection.localDescription)
}

socket.on('receiverAnswer', (answer) => {                //接收answer
  hostPeerConnection.setRemoteDescription(answer);
});

hostPeerConnection.onicecandidate=(event)=>{            //建立通信：Interactive Connectivity Establishment
    if(event.candidate){
        socket.emit("hostSendCandidate",event.candidate)
    }
}
socket.on("hostReceiverCandidate",(candidate)=>{
    hostPeerConnection.addIceCandidate(new RTCIceCandidate(candidate))
})


//作为观众
const audiencePeerConnection= new RTCPeerConnection()
socket.on("receiverOffer",(offer)=>{                          //接收offer
    audiencePeerConnection.setRemoteDescription(offer)
    sendAnswer()
})
const sendAnswer=async ()=>{                                  //发送answet
    const answer= await audiencePeerConnection.createAnswer()
    await audiencePeerConnection.setLocalDescription(answer)
    await socket.emit("sendAnswer",audiencePeerConnection.localDescription)
}

audiencePeerConnection.onicecandidate=(event)=>{              //建立通信：Interactive Connectivity Establishment
    if(event.candidate){
        socket.emit("audienceSendCandidate",event.candidate)
    }
}
socket.on("audienceReceiverCandidate",(candidate)=>{
    audiencePeerConnection.addIceCandidate(new RTCIceCandidate(candidate))
})
audiencePeerConnection.ontrack=(event)=>{
    videoRef2.value.srcObject=event.streams[0]
}

const shareScreen = async () => {
    stream.value = await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
    videoRef.value.srcObject = stream.value
    sendOffer(stream.value)
}
const stopShareScreen=()=>{
    if(stream.value){
        const videoTracks=stream.value.getVideoTracks()
        const audioTracks=stream.value.getAudioTracks()
        videoTracks.forEach(track=>{
            track.stop()
        })
        audioTracks.forEach(track=>{
            track.stop()
        })
        stream.value=null
        videoRef.value.srcObject=null
    }else{
        ElMessage.error("你没有打开摄像头")
    }
}
</script>

<template>
    <div class="videoroom_container">
        <h1 class="title">直播间</h1>
        <div class="main">
            <div class="user_list_aside">
                <div v-for="(value, key) in userMap" :key="key" class="user_title">{{ value }}</div>
            </div>
            <div class="video_container">
                <div class="operator_container">
                    <el-button type="primary" size="small" @click="shareScreen">视频共享</el-button>
                    <el-button type="primary" size="small" @click="stopShareScreen">停止共享</el-button>
                </div>
                <video src="#" controls autoplay class="video_window" ref="videoRef"></video>
                <video src="#" controls autoplay class="video_window" ref="videoRef2"></video>
            </div>
        </div>
    </div>
</template>

<style scoped lang='less'>
.videoroom_container {
    height: 100vh;
    width: 99vw;
    display: flex;
    flex-direction: column;
    .title {
        width: 100%;
        height: 50px;
        line-height: 50px;
        font-size: 20px;
        font-weight: 800;
        text-align: center;
        background-color: #ccc;
    }

    .main {
        flex: 1;
        display: flex;
        overflow: auto;
        .user_list_aside {
            height: 100%;
            width: 200px;
            overflow: auto;
            background-color: #eee;
            .user_title {
                height: 50px;
                line-height: 50px;
                text-align: center;
            }
        }

        .video_container {
            position: relative;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            overflow: auto;

            .operator_container {
                position: absolute;
                margin-top: 5px;
                left: 0;
                top: 0;
            }

            .video_window {
                height: 50%;
            }
        }

    }
}
</style>